import flash.filesystem.*;

import mx.controls.*;
import mx.events.CloseEvent;

private function openProjectBrowseClick():void {
	var myFile:File = new File();
	 
	var ftFilter:FileFilter = new FileFilter("FlexTrans Project", "*.flextrans");
	myFile.addEventListener(Event.SELECT, openProjectFile);
	myFile.browseForOpen("Open project file", [ftFilter]);
}

private function openProjectFile(event:Event):void 
{
    var newFile:File = event.target as File;
    var str:String;
	var stream:FileStream = new FileStream();
	
	projectFilename = newFile.nativePath;
	
    stream.open(newFile, FileMode.READ);
    project = new XML(stream.readUTFBytes(newFile.size));
    project.normalize();
    stream.close();
    
    masterLocale = project.properties[0].@masterlocale;
	
	currentState = "openProject"; 
}

private function deleteLocale():void {
	if (opLocaleDG.selectedIndex >= 0) {
		delete project.locale.(@code == opLocaleDG.selectedItem.@code)[0];
		projectModified = true;
	}
}

private function saveProject():void {
	var str:String;
	var newFile:File = new File(projectFilename);
	var stream:FileStream = new FileStream();
	
	project.normalize();
	str = project.toXMLString();
	
    stream.open(newFile, FileMode.WRITE);
    stream.writeUTFBytes(str);
    stream.close();
    projectModified = false;
}

private function closeProject():void {
	if (projectModified) {
		Alert.show("The project has been modified, would you like to save it?", "Close project", Alert.YES | Alert.NO | Alert.CANCEL, this, alertHandler);
	}
	else {
		closeProjectFinal();
	}
}

private function closeProjectFinal():void {
	project = new XML();
	masterLocale = "";
	projectFilename = "";
	if (currentState == "openProject") {
		clearAllInMlTab();
		clearAllInTrTab();
	}
	projectModified = false;
	
	currentState = "startScreen";
}

private function alertHandler(event:CloseEvent):void {
	switch (event.detail) {
		case Alert.YES:
			saveProject();
			closeProjectFinal();
			break;
		case Alert.NO:
			closeProjectFinal();
			break;
		case Alert.CANCEL:
		default:
			break;	
	}
}

private function generateFiles():void {
	for each (var l:XML in project.locale) {
		var fileName:String = l.@file;
		var file:File = new File(fileName);
	    var str:String;
		var stream:FileStream = new FileStream();
		
	    stream.open(file, FileMode.WRITE);
	    
	    for each (var e:XML in l.entry) {
	    	str = e.@name.toString() + "=" + e.@text.toString() + "\n";
	    	stream.writeUTFBytes(str);
	    }
	    stream.close();
	}
	Alert.show("Files written.");
}